package mongo.core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

import com.google.gson.Gson;

/**
 * mongodb 的操作核心类
 * @author Administrator
 *
 */
public class MongoManager {
	private static final String _UUID = "_uuid";
	/**
	 * 获取表的所有数据
	 */
	public List<Map> loadAllByTable(String path, String tableName) throws Exception {
		Gson gson = new Gson();
		List<Map> list = new ArrayList<Map>();
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(new FileInputStream(path));
		Element root = document.getRootElement();
		List<Element> childElement = root.getChildren();
		for(Element element : childElement) {
			if(element.getAttributeValue("name").equals(tableName)) {
				List<Element> elements = element.getChildren();
				for(Element e : elements) {
					String text = e.getText();
					if(text == null){
						break;
					}
					Map map = gson.fromJson(text, Map.class);
					list.add(map);
				}
			}
		}
		return list;
	}
	/**
	 * 插入数据
	 * @param path
	 * @param tableName
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public boolean add(String path, String tableName, Object obj) throws Exception {
		boolean flag = false;
		Gson gson = new Gson();
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(new FileInputStream(path));
		Element root = document.getRootElement();
		System.out.println("root:"+root.getName());
		List<Element> childElement = root.getChildren();
		for(Element element : childElement) {
			System.out.println(element.getAttributeValue("name"));
			if(element.getAttributeValue("name").equals(tableName)) {
				Map map = new HashMap();
				map.put(_UUID, UUID.randomUUID().toString());
				//放入xml中
				Element data = new Element("data");
				System.out.println(gson.toJson(obj));
				Map added = gson.fromJson(gson.toJson(obj), Map.class);
				System.out.println(added.get("age"));
				map.putAll(added);
				data.addContent(gson.toJson(map));
				System.out.println(gson.toJson(map));
				element.addContent(data);//添加入table的末尾
				System.out.println(data.getAttributes());
				System.out.println(element.getText());
			}
		}
		
		//回写
		XMLOutputter out = new XMLOutputter();
		out.output(document, new FileOutputStream(path));
		flag = true;
		System.out.println("insert data success");
		return flag;
	}
	/**
	 * 更新数据
	 * @param path
	 * @param tableName
	 * @param obj
	 * @throws Exception
	 */
	public void update(String path, String tableName, Object obj) throws Exception {
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(new FileInputStream(path));
		Element root = document.getRootElement();
		List<Element> childElement = root.getChildren();
		
		Gson gson = new Gson();
		Map objMap = gson.fromJson(gson.toJson(obj), Map.class);
		for(Element element : childElement) {
			if(element.getAttributeValue("name").equals(tableName)) {
				List<Element> elements = element.getChildren();
				for(Element e : elements){
					//获取到data数据
					String xmlData = e.getText();
					Map xmlMap = gson.fromJson(xmlData, Map.class);
					//获取data的uuid值，与传入的uuid比较
					if(xmlMap.get(_UUID).equals(objMap.get(_UUID))) {
						Element newData = new Element("data");
						System.out.println("old data: " + gson.toJson(xmlMap));
						xmlMap.putAll(objMap);
						xmlMap = objMap;
						System.out.println("new data: " + gson.toJson(xmlMap));
						newData.setText(gson.toJson(xmlMap));
						//将原数据删除
						element.removeContent(e);
						//插入新数据
						element.addContent(newData);
						break;
					}
				}
			}
		}
		XMLOutputter out = new XMLOutputter();
		out.output(document, new FileOutputStream(path));
		System.out.println("update data success");
	}
    /**
     * 删除数据
     * @param path
     * @param tableName
     * @param obj
     * @throws Exception
     */
	public void delete(String path, String tableName, Object obj) throws Exception {
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(new FileInputStream(path));
		
		Element root = document.getRootElement();
		List<Element> childElement = root.getChildren();
		Gson gson = new Gson();
		Map objMap = gson.fromJson(gson.toJson(obj), Map.class);
		for(Element element : childElement) {
			if(element.getAttributeValue("name").equals(tableName)) {
				List<Element> elements = element.getChildren();
				for(Element e : elements) {
					Map xmlMap = gson.fromJson(e.getText(), Map.class);
					if(objMap.get(_UUID).equals(xmlMap.get(_UUID))) {
						element.removeContent(e);
						break;
					}
				}
			}
		}
		
		XMLOutputter out = new XMLOutputter();
		out.output(document, new FileOutputStream(path));
		System.out.println("delete data success");
	}
	/**
	 * 创建数据库
	 * @param path
	 * @param tableName
	 * @throws Exception
	 */
	public void createDataBase(String path, String tableName) throws Exception {
		Document document = new Document();
		Element root = new Element("database");
		Element sort1 = new Element("table");
		sort1.setAttribute("name", tableName);
		Element sort2 = new Element("table");
		sort2.setAttribute("name", "system.indexs");
		Element sort3 = new Element("table");
		sort3.setAttribute("name", "system.users");

		root.addContent(sort1);
		root.addContent(sort2);
		root.addContent(sort3);

		document.setRootElement(root);
		XMLOutputter out = new XMLOutputter();
		out.output(document, new FileOutputStream(path));
		System.out.println("create database-table success");
	}


} 
